package faircat.android.exphone;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.database.Cursor;
import android.net.Uri;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.IntentFilter;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnClickListener;
import android.content.Intent;
import android.widget.ImageButton;

public class SMSActivity extends ListActivity implements OnItemClickListener, OnClickListener {
	ContentResolver mCr;
	Cursor cursor=null;
	int mSimCard = 1;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms);
		
		//String[] projection = new String[] {"_id", "address", "person", "body"};
		
		//Cursor cursor = managedQuery(Uri.parse("content://sms/inbox"),
		//		projection, null, null, "date desc");
		
		mCr = this.getContentResolver();
		
		updateSim2();
		
		//findViewById(R.id.sms_new).setOnClickListener(this);
		//findViewById(R.id.contacts).setOnClickListener(this);
		//findViewById(R.id.dial).setOnClickListener(this);
		//findViewById(R.id.sim1).setOnClickListener(this);
		//findViewById(R.id.sim2).setOnClickListener(this);
		
		//((ImageButton)findViewById(R.id.sim2)).setSelected(true);

		IntentFilter filter = new IntentFilter();
		filter.addAction(ExSMS.ACTION_UPDATE_SMS);
		registerReceiver(mReceiver, filter);
	}	
	
	public void onDestroy(){
		if(!cursor.isClosed()){
			cursor.close();
		}
		unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	
	public void updateSim1(){
		Cursor cursor = mCr.query(Uri.parse("content://sms"),
				new String[]{"threads._id, threads.date,threads.message_count,threads.recipient_ids, threads.snippet,sms.person,sms.address,sms.date,sms.body from threads,sms where sms.thread_id=threads._id group by threads._id order by sms.date desc--"}, 
				null, null, null);
		
		ListView lv = (ListView)findViewById(R.id.sms_list);
		SimpleCursorAdapter adapter = new SmsCursorAdapter(
				this, R.layout.sms_entry, cursor,
				new String[]{"address",  "body"},
				new int[]{R.id.sms_entry_name, R.id.sms_entry_brief}
				);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(this);
		cursor.close();
	}
	
	public void updateSim2(){
		{
			
			Log.d("sdafsddsfsdfafafds", "ss=updateSim2");

				if(AT.smscontent!=null)
				{
					Log.d("sdafsddsfsdfafafds", "ss=11");

					String aa=AT.smscontent;
					Log.i("asdfasfdsafdasdf", aa);
					String[] temp=aa.split("CMGL:");
					Log.i("asdfasfdsafdasdf", "AAA="+temp.length);

					for(int i=1;i<=temp.length-1;i++)
					{
						Log.i("asdfasfdsafdasdf", "AAA="+temp[1]);

						Pattern pattern = Pattern.compile("\\ [0-9]+,, [0-9]+\\s+([0-9A-F]+)\\s");
						Matcher matcher = pattern.matcher((String)temp[i]);
						if( matcher.find())
						{
							String pduString = matcher.group(1);					
							Util.SMS sms = new Util.SMS(pduString);

							SimpleDateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); 
							long time = 0;
							try{
								Date date = df.parse(sms.strTime);
								time = date.getTime();
							}
							catch(ParseException e){
								
							}
							Log.i("ExPhoneService", "time="+time);
							
							if(sms.strPhone.charAt(0)=='+'){
								if((sms.strPhone.charAt(1)=='8')&&(sms.strPhone.charAt(2)=='6'))
								{
									sms.strPhone=sms.strPhone.substring(3);
								}
							}
							ExSMS q = new ExSMS(SMSActivity.this);
							q.add(sms.strPhone, time, 1, 0, sms.strMsg);
							q.close();
						}
					}
					//Intent intent = new Intent();
					//intent.setAction(ExPhoneService.ACTION_DELETE_SMSALL);
					//sendBroadcast(intent);	
					AT.smscontent=null;
				}  	    					
		}
		ExSMS q = new ExSMS(this);

		 cursor = q.queryAll();
		
		ListView lv = getListView();
		SimpleCursorAdapter adapter = new SmsCursorAdapter(
				this, R.layout.sms_entry, cursor,
				new String[]{"address", "body"},
				new int[]{R.id.sms_entry_name, R.id.sms_entry_brief}
				);
		lv.setAdapter(adapter);
		lv.setOnItemClickListener(this);
		Log.d("sdfasdfas", "sdf="+cursor.getCount());
		//cursor.close();
		
		q.close();
	}
	
	public void onItemClick(AdapterView<?> view, View v, int arg2, long arg3){
		Intent i = new Intent(this, SMSThreadActivity.class);
		i.putExtra("phonenumber", (String)v.getTag());

		TextView tvName = (TextView)v.findViewById(R.id.sms_entry_name);
		i.putExtra("name", (String)tvName.getTag());
		
		i.putExtra("sim", mSimCard);
		
		startActivity(i);
	}
	
	public void onResume() {
		// TODO Auto-generated method stub
		Log.i("aaaaaaa", "time=");
		//mSimCard = 0;
		
	
		super.onResume();
		
		if(mSimCard==0)
		{
			updateSim1();
		}
		else if(mSimCard==1)
		{
			updateSim2();
		}		
	}

	public void onClick(View view){
		Intent i;
	}
	
	class SmsCursorAdapter extends SimpleCursorAdapter{
		public SmsCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to){
			super(context, layout, c, from, to);
		}

		public void bindView(View view, Context context, Cursor cursor){
			super.bindView(view, context, cursor);
			int addr_index = cursor.getColumnIndex("address");
			String address = cursor.getString(addr_index);
			int cnt_index = cursor.getColumnIndex("message_count");
			int cnt = cursor.getInt(cnt_index);
			int time_index = cursor.getColumnIndex("date");
			Long time = cursor.getLong(time_index);
			//TextView tvTime = (TextView)view.findViewById(R.id.sms_entry_time);
			Long now = System.currentTimeMillis();
			if( now - time >= 24 * 3600 * 1000){
				//tvTime.setText(DateUtils.formatDateTime(context, time, DateUtils.FORMAT_SHOW_DATE));
			}
			else{
				//tvTime.setText(DateUtils.formatDateTime(context, time, DateUtils.FORMAT_SHOW_TIME));
			}
			
			view.setTag(address);
			if( address != null ){		
				if( address.startsWith("+86")){
					address = address.substring(3);	
				}	
				Cursor contactData = mCr.query(Phone.CONTENT_URI, 
						new String[]{Phone.DISPLAY_NAME}, 
						Phone.NUMBER+" like '%"+address+"'", null, null);
				TextView tvName = (TextView)view.findViewById(R.id.sms_entry_name);
				if( contactData.moveToFirst()){
					int name_index = contactData.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
					String name = contactData.getString(name_index);
					tvName.setText(name);
					tvName.setTag(name);
				}
				else{
					tvName.setTag(null);
				}
				if( cnt > 1 ){
					tvName.append("("+cnt+")");
				}
				if( !contactData.isClosed()){
					contactData.close();
				}
			}
		}
	}
	
	BroadcastReceiver mReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent){
			String action = intent.getAction();
			if( ExSMS.ACTION_UPDATE_SMS.equals(action)){
				if( mSimCard == 1 ){
					updateSim2();
				}
			}
		}
	};
}
